const { decode } = require("../utils/base64_tool");
const { info } = require("../utils/log_tool");
const { parse } = require("../utils/parse_tool");
const { BaseCommand } = require("./base");

class EnvOptionalCommand extends BaseCommand {
    async execute() {
        const data = this.selfData;
        const updatedData = {};
        for (const k in data) {
            const envVal = this.shareData.ENV[k];
            let defValue = data[k];
            if (defValue == null) {
                defValue = "";
            }
            if (envVal == null) {
                updatedData[k] = defValue;
            } else {
                const toType = typeof defValue;
                switch (toType) {
                    case "string": {
                        updatedData[k] = envVal;
                        break;
                    }
                    case "number": {
                        updatedData[k] = parseFloat(envVal);
                        break;
                    }
                    case "boolean": {
                        if (envVal && envVal !== "false" && envVal !== "0") {
                            updatedData[k] = true;
                        } else {
                            updatedData[k] = false;
                        }
                        break;
                    }
                    case "object": {
                        updatedData[k] = await parse(envVal, "yaml");
                        break;
                    }
                    default: {
                        throw `unsupport type ${toType}`;
                        break;
                    }
                }
            }
        }
        for (const k in updatedData) {
            this.shareData[k] = updatedData[k];
        }
        return updatedData;
    }
}

module.exports = {
    EnvOptionalCommand,
};
